$(document).ready(function () {
    // 点击按钮打开新增模拟器弹窗
    $("#addSimulatorBtn").click(function () {
        $("#addSimulatorModal").show();
    });

    // 点击 <span> (x) 关闭弹窗
    $(".close").click(function () {
        $(this).closest(".modal").hide();
    });

    // 点击窗口外部关闭弹窗
    $(window).click(function (event) {
        if ($(event.target).is("#addSimulatorModal") || $(event.target).is("#setFieldsModal")) {
            $(event.target).hide();
        }
    });

    // 表单提交事件
    $("#addSimulatorForm").submit(function (event) {
        event.preventDefault();
        var formData = {
            id: $("#id").val(),
            name: $("#name").val(),
            type: $("#type").val(),
            port: $("#port").val(),
            poolSize: $("#poolSize").val(),
            overTcp: $("#overTcp").is(":checked"),
            uintId: $("#uintId").val()
        };

        // 检查端口和ID是否重复
        $.ajax({
            url: '/modbus/checkPort',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({id: formData.id, port: formData.port}),
            success: function (response) {
                if (response.isDuplicate) {
                    alert("端口或ID已存在，请使用不同的端口或ID。");
                } else {
                    // 如果端口和ID不重复，则提交表单
                    $.ajax({
                        url: '/modbus/create',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(formData),
                        success: function (data) {
                            alert("模拟器已新增！");
                            $("#addSimulatorModal").hide();
                            loadSimulatorList(); // 刷新模拟器列表
                        },
                        error: function (error) {
                            console.error('Error:', error);
                        }
                    });
                }
            },
            error: function (error) {
                console.error('Error:', error);
            }
        });
    });

    // 加载模拟器列表
    function loadSimulatorList() {
        $.ajax({
            url: '/modbus/list',
            type: 'GET',
            success: function (data) {
                var table = $("#simulatorTable tbody");
                // 清空现有的表格内容
                table.html('');
                // 添加新的模拟器数据
                data.forEach(function (simulator) {
                    var row = `
                        <tr>
                            <td>${simulator.id}</td>
                            <td>${simulator.name}</td>
                            <td>${simulator.type}</td>
                            <td>${simulator.port}</td>
                            <td>
                                <button onclick="openSetFieldsModal('${simulator.id}')">设置字段</button>
                                </td>
                            <td>
                                <button onclick="cloneSimulator('${simulator.id}')" style="background: #03A9F4;">克隆</button>
                                <button onclick="stopSimulator('${simulator.id}')" style="background: #fa9f1b; ${simulator.io === 0 ? '' : 'display: none'}"  >停止</button>
                                <button onclick="startSimulator('${simulator.id}')" style="background: #26A69A; ${simulator.io === 1 ? '' : 'display: none'}" >启动</button>
                    
                                <button onclick="deleteSimulator('${simulator.id}')" style="background: #DF5645">删除</button>
                            </td>
                        </tr>
                    `;
                    table.append(row);
                });
            },
            error: function (error) {
                console.error('Error:', error);
            }
        });
    }

    // 页面加载时获取模拟器列表
    loadSimulatorList();

    // 打开设置字段弹窗并回显字段数据
    window.openSetFieldsModal = function (simulatorId) {
        $.ajax({
            url: '/modbus/view/field',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({simulatorId: simulatorId}),
            success: function (response) {
                var fieldsContainer = $("#fieldsContainer");
                fieldsContainer.html(''); // 清空现有的字段行
                response.fields.forEach(function (field) {
                    var newRow = `
                        <div class="fieldRow">
                            <label for="ref"  style="width: 100px">地址:</label>
                            <input type="text" name="ref" style="width: 100px" value="${field.ref}" required>
                            <label for="name" style="width: 100px">名:</label>
                            <input type="text" name="name"  style="width: 100px" value="${field.name}" required>
                            <label for="before" style="width: 150px">初始值:</label>
                            <input type="text" name="before"  style="width: 100px" value="${field.before}" required>
                            <label for="extendInfo" style="width: 100px">时段</label>
                            <textarea  name="extendInfo" style="width: 800px" >${field.extendInfo}</textarea>
                            <label for="change" style="width: 100px">变形:</label>
                            <select name="change" style="width: 100px" required>
                                <option value="range" ${field.change === 'range' ? 'selected' : ''}>range</option>
                                <option value="acc" ${field.change === 'acc' ? 'selected' : ''}>acc</option>
                            </select> 
                            <button type="button" onclick="removeFieldRow(this)" style="width: 200px;background: #fa9f1b">删除</button>
                        </div>
                    `;
                    fieldsContainer.append(newRow);
                });
                $("#setFieldsModal").data('simulatorId', simulatorId).show();
            },
            error: function (error) {
                console.error('Error:', error);
            }
        });
    };

    // 动态添加字段行
    window.addFieldRow = function () {
        var newRow = `
            <div class="fieldRow">
                <label for="ref" style="width: 100px">地址:</label>
                <input type="text" name="ref" style="width: 100px" required>
                <label for="name" style="width: 100px">名:</label>
                <input type="text" name="name"  style="width: 100px" required>
                <label for="before" style="width: 150px">初始值:</label>
                <input type="text" name="before"  style="width: 100px" required>
                <label for="extendInfo" style="width: 100px">时段</label>
                <textarea  name="extendInfo" style="width: 800px" ></textarea>
                <label for="change" style="width: 100px">变形:</label>
                <select name="change" style="width: 100px" required>
                    <option value="range" }>range</option>
                    <option value="acc" }>acc</option>
                </select> 
                <button type="button" onclick="removeFieldRow(this)" style="width: 200px;background: #fa9f1b">删除</button>
            </div>
        `;
        $("#fieldsContainer").append(newRow);
    };

    // 删除字段行
    window.removeFieldRow = function (button) {
        $(button).closest(".fieldRow").remove();
    };

    // 设置字段表单提交事件
    $("#setFieldsForm").submit(function (event) {
        event.preventDefault();
        var fields = [];
        $(".fieldRow").each(function () {
            var field = {
                ref: $(this).find("input[name='ref']").val(),
                name: $(this).find("input[name='name']").val(),
                before: $(this).find("input[name='before']").val(),
                extendInfo: $(this).find("textarea[name='extendInfo']").val(),
                change: $(this).find("select[name='change']").val(),
            };
            fields.push(field);
        });

        var simulatorId = $("#setFieldsModal").data('simulatorId');

        // 提交字段数据到 /modbus/update/field 接口
        $.ajax({
            url: '/modbus/update/field',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({simulatorId: simulatorId, fields: fields}),
            success: function (data) {
                alert("字段已更新！");
                $("#setFieldsModal").hide();
            },
            error: function (error) {
                console.error('Error:', error);
            }
        });
    });

    // 删除模拟器
    window.deleteSimulator = function (id) {
        if (confirm("确定要删除这个模拟器吗？")) {
            $.ajax({
                url: '/modbus/delete',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({id: id}),
                success: function (data) {
                    alert("模拟器已删除！");
                    loadSimulatorList(); // 刷新模拟器列表
                },
                error: function (error) {
                    console.error('Error:', error);
                }
            });
        }
    };
    window.cloneSimulator = function (id) {
        var num1 = prompt('请输入复制份数：');
        console.log(num1 + " " + id);
        if (num1 !== "" || num1 != null) {
            $.ajax({
                url: '/modbus/clone',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({id: id, num: num1}),
                success: function (data) {
                    alert("模拟器复制" + num1 + "份 完成");
                    loadSimulatorList(); // 刷新模拟器列表
                },
                error: function (error) {
                    console.error('Error:', error);
                }
            });
        }
    }
    window.stopSimulator = function (id) {
        $.ajax({
            url: '/modbus/stop',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({id: id}),
            success: function (data) {
                loadSimulatorList(); // 刷新模拟器列表
            },
            error: function (error) {
                console.error('Error:', error);
            }
        });
        loadSimulatorList();
    }
    window.startSimulator = function (id) {
        $.ajax({
            url: '/modbus/start',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({id: id}),
            success: function (data) {
                loadSimulatorList(); // 刷新模拟器列表
            },
            error: function (error) {
                console.error('Error:', error);
            }
        });
        loadSimulatorList();
    }
});
